import { CheckCircleOutlined, PlusCircleOutlined } from "@ant-design/icons"
import { history, useIntl, useModel } from "@umijs/max"
import {
  App,
  Button,
  Divider,
  Form,
  Input,
  InputNumber,
  Popconfirm,
  Select,
  Table,
  Tooltip,
  Typography
} from "antd"
import React, { useEffect, useState } from "react"

interface EditableCellProps extends React.HTMLAttributes<HTMLElement> {
  editing: boolean
  dataIndex: string
  title: any
  inputType: "number" | "text" | "select"
  record: any
  index: number
}

const EditableCell: React.FC<React.PropsWithChildren<EditableCellProps>> = ({
  editing,
  dataIndex,
  title,
  inputType,
  record,
  index,
  children,
  ...restProps
}) => {
  let inputNode
  if (inputType === "number") {
    inputNode = <InputNumber />
  } else if (inputType === "text") {
    inputNode = <Input />
  } else {
    // select相关
    if (dataIndex === "unit") {
      inputNode = (
        <Select
          options={[
            { value: "mm", label: "mm" },
            { value: "inch", label: "inch" }
          ]}
        />
      )
    } else if (dataIndex === "isReverse") {
      inputNode = (
        <Select
          options={[
            { value: "否", label: "否" },
            { value: "是", label: "是" }
          ]}
        />
      )
    }
  }

  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item
          name={dataIndex}
          style={{ margin: 0 }}
          rules={[
            {
              required: true,
              message: `Please Input ${title}!`
            }
          ]}
        >
          {inputNode}
        </Form.Item>
      ) : (
        children
      )}
    </td>
  )
}

// 创建一个带有 tooltip 的单元格组件
const EllipsisCell: React.FC<{ value: any }> = ({ value }) => {
  return (
    <Tooltip title={value?.toString()}>
      <div
        style={{
          maxWidth: "100%",
          overflow: "hidden",
          textOverflow: "ellipsis",
          whiteSpace: "nowrap"
        }}
      >
        {value}
      </div>
    </Tooltip>
  )
}

const OrderForm: React.FC = () => {
  const [form] = Form.useForm()
  const { orderChoosed, searchOrders, totalOrders, updateProduceData, showTotalOrders } =
    useModel("produceModel")

  // 根据 showTotalOrders 决定显示哪个数据源
  const orderShow = showTotalOrders ? totalOrders : searchOrders

  const [editingKey, setEditingKey] = useState<number>(0)
  const [isReload, setIsReload] = useState(false)
  const { callPy, wsIsOpenRef } = useModel("websocketModel")
  const { message } = App.useApp()
  const intl = useIntl()

  // 添加数据加载的 useEffect
  useEffect(() => {
    console.log("OrderForm 表单初始化,isReload:", isReload)
    const fetchData = async () => {
      try {
        const response = await callPy("db", "get_total_order_show_from_web", [])
      } catch (error) {
        console.log("数据加载失败", error)
      }
    }

    if (wsIsOpenRef.current) {
      fetchData()
    } else {
      // 过1秒之后再尝试获取数据
      setTimeout(() => {
        fetchData()
      }, 500)
    }
  }, [isReload])

  const isEditing = (record: any) => record.key === editingKey

  const edit = (record: any) => {
    form.setFieldsValue({ ...record })
    setEditingKey(record.key)
    updateProduceData({ isOperateMode: true })
  }
  const handleOnRow = (record: any) => ({
    onDoubleClick: (event: any) => {
      console.log("record", record)
      updateProduceData({ orderChoosed: record })
    }
  })

  const cancel = () => {
    setIsReload(!isReload)
    updateProduceData({ showTotalOrders: true })
    setEditingKey(0)
  }

  const save = async (key: number) => {
    try {
      const row = await form.validateFields()
      const newData = { ...row, key: key }
      const response = await callPy("produce", "save_order_from_web", [newData])
      setEditingKey(0)
      if (response.state) {
        message.success(intl.formatMessage({ id: "orderForm.saveSuccess" }))
        updateProduceData({ searchOrders: response.data[0] })
        updateProduceData({ totalOrders: response.data[1] })
        updateProduceData({ orderChoosed: response.data[0][0] })
      } else {
        message.error(intl.formatMessage({ id: "orderForm.saveFail" }) + response.info, 3)
      }
    } catch (errInfo) {
      console.log("Validate Failed:", errInfo)
    } finally {
      updateProduceData({ isOperateMode: false })
    }
  }

  const remove = async (key: number) => {
    try {
      const response = await callPy("db", "delete_order_from_web", [key])
      if (response.state) {
        message.success(intl.formatMessage({ id: "orderForm.deleteSuccess" }))
      } else {
        message.error(intl.formatMessage({ id: "orderForm.deleteFail" }) + response.info)
      }
      setIsReload(!isReload)
    } catch (error) {
      console.log(error)
    } finally {
      updateProduceData({ isOperateMode: false })
    }
  }

  const changeOrder = async () => {
    const response = await callPy("produce", "change_order_from_web", [orderChoosed.key])
    if (response.state) {
      history.push("/produce")
    } else {
      message.error(
        intl.formatMessage({ id: "orderForm.changeOrderFail" }) + response.info,
        5
      )
    }
  }

  const addRow = async () => {
    try {
      const myDate = new Date()
      const newData = {
        key: myDate.getTime(),
        orderId: "",
        width: "", //内层尺寸
        height: "", // 内层尺寸
        unit: "mm", // 英寸
        firstEdge: 0, // 第一刀留边宽度
        secondEdge: 0, // 第二刀留边宽度
        thirdEdge: 0, // 第三刀留边宽度
        fourthEdge: 0, // 第四刀留边宽度
        calcWidth: 0, // 识别宽
        calcHeight: 0, // 识别高
        planCount: 0, // 计划数量
        finished: 0 // 完成数量
      }
      // 直接更新 workingOrder
      updateProduceData({ searchOrders: [newData], showTotalOrders: false })
      // 使用edit函数设置表单值
      edit(newData)
    } catch (error) {
      console.log(error)
    } finally {
      updateProduceData({ isOperateMode: true })
    }
  }

  const columns = [
    {
      title: intl.formatMessage({ id: "orderForm.orderId" }),
      dataIndex: "orderId",
      editable: true,
      inputType: "text",
      width: 120,
      fixed: "left",
      ellipsis: true,
      render: (value: any) => <EllipsisCell value={value} />
    },
    {
      title: intl.formatMessage({ id: "orderForm.width" }),
      dataIndex: "width",
      editable: true,
      inputType: "number",
      width: 75,
      ellipsis: true
    },
    {
      title: intl.formatMessage({ id: "orderForm.height" }),
      dataIndex: "height",
      editable: true,
      inputType: "number",
      width: 75,
      ellipsis: true
    },
    {
      title: intl.formatMessage({ id: "orderForm.unit" }),
      dataIndex: "unit",
      editable: true,
      inputType: "select",
      width: 70,
      ellipsis: true
    },
    {
      title: intl.formatMessage({ id: "orderForm.firstEdge" }),
      dataIndex: "firstEdge",
      editable: true,
      inputType: "number",
      width: 90
    },
    {
      title: intl.formatMessage({ id: "orderForm.secondEdge" }),
      dataIndex: "secondEdge",
      editable: true,
      inputType: "number",
      width: 90
    },
    {
      title: intl.formatMessage({ id: "orderForm.thirdEdge" }),
      dataIndex: "thirdEdge",
      editable: true,
      inputType: "number",
      width: 90
    },
    {
      title: intl.formatMessage({ id: "orderForm.fourthEdge" }),
      dataIndex: "fourthEdge",
      editable: true,
      inputType: "number",
      width: 90
    },
    {
      title: intl.formatMessage({ id: "orderForm.calcWidth" }),
      dataIndex: "calcWidth",
      editable: true,
      inputType: "number",
      width: 70
    },
    {
      title: intl.formatMessage({ id: "orderForm.calcHeight" }),
      dataIndex: "calcHeight",
      editable: true,
      inputType: "number",
      width: 70
    },
    {
      title: intl.formatMessage({ id: "orderForm.planCount" }),
      dataIndex: "planCount",
      editable: true,
      inputType: "number",
      width: 80
    },
    {
      title: intl.formatMessage({ id: "orderForm.finished" }),
      dataIndex: "finished",
      editable: true,
      inputType: "number",
      width: 80
    },
    {
      title: intl.formatMessage({ id: "orderForm.action" }),
      fixed: "right",
      width: 120,
      render: (_: any, record: any) => {
        const editable = isEditing(record)
        return editable ? (
          <span>
            <Typography.Link
              onClick={() => save(record.key)}
              style={{ marginInlineEnd: 8 }}
            >
              {intl.formatMessage({ id: "orderForm.save" })}
            </Typography.Link>
            <Popconfirm title="确定取消吗?" onConfirm={cancel}>
              <a>{intl.formatMessage({ id: "orderForm.cancel" })}</a>
            </Popconfirm>
          </span>
        ) : (
          <span>
            <Typography.Link disabled={editingKey !== 0} onClick={() => edit(record)}>
              {intl.formatMessage({ id: "orderForm.edit" })}
            </Typography.Link>
            <Divider type="vertical" />
            <Popconfirm title="确认删除吗" onConfirm={() => remove(record.key)}>
              <a>{intl.formatMessage({ id: "orderForm.delete" })}</a>
            </Popconfirm>
          </span>
        )
      }
    }
  ]

  const mergedColumns: any = columns.map((col) => {
    if (!col.editable) {
      return col
    }
    return {
      ...col,
      onCell: (record: any) => ({
        record,
        inputType: col.inputType,
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record)
      })
    }
  })

  return (
    <Form form={form} component={false}>
      <Table<any>
        components={{
          body: { cell: EditableCell }
        }}
        bordered
        dataSource={orderShow}
        columns={mergedColumns}
        rowClassName="editable-row"
        onRow={handleOnRow}
        size="middle"
        pagination={
          showTotalOrders
            ? {
                onChange: cancel,
                pageSize: 8
              }
            : false
        }
        footer={() => (
          <div
            style={{
              display: "flex",
              alignItems: "center",
              justifyContent: "center", // 使内容居中
              gap: 16, // 设置按钮之间的间距
              height: 40
            }}
          >
            {orderChoosed ? (
              <span
                style={{
                  fontSize: 18,
                  width: 350,
                  color: "#A020F0",
                  marginRight: 16 // 与按钮保持间距
                }}
              >
                {intl.formatMessage({ id: "orderForm.selected" })}
                <span style={{ color: "#FF0000", marginLeft: 15 }}>
                  {orderChoosed.orderId}
                </span>
              </span>
            ) : (
              <span
                style={{
                  width: 300,
                  fontSize: 18,
                  color: "#A020F0",
                  marginRight: 16 // 与按钮保持间距
                }}
              >
                {intl.formatMessage({ id: "orderForm.doubleClickTip" })}
              </span>
            )}
            <Button
              size="large"
              onClick={changeOrder}
              style={{ width: 200 }}
              type="dashed"
              icon={<CheckCircleOutlined />}
              disabled={!orderChoosed}
            >
              {intl.formatMessage({ id: "orderForm.changeOrder" })}
            </Button>
            <Button
              size="large"
              onClick={addRow}
              style={{ width: 200, marginLeft: 15 }}
              type="dashed"
              icon={<PlusCircleOutlined />}
            >
              {intl.formatMessage({ id: "orderForm.addOrder" })}
            </Button>
          </div>
        )}
      />
    </Form>
  )
}

export default () => (
  <App>
    <OrderForm />
  </App>
)
